import { defineStore } from "pinia";
import { reactive } from "vue";
import { useMapStore } from "./map";
import { useCargoStore } from "./cargo";

interface Player {
    x:number
    y:number
}

export const usePlayerStore = defineStore('playerStore',() => {
    const { isWall } = useMapStore()
    const { findCargo,moveCargo } = useCargoStore()
    const player = reactive<Player>({
        x:0,
        y:0
    })
    function _move(dx:number,dy:number) {
        const nextPosition = { x:player.x + dx, y:player.y + dy }
        if(isWall(nextPosition)) return
        const cargo:any = findCargo(nextPosition)
        if(cargo) {
            const isMoveCargo = moveCargo(cargo,dx,dy)
            if(!isMoveCargo) return
        }
        player.x += dx
        player.y += dy
    }
    function movePlayerToUp() {
        _move(0,-1)
    }
    function movePlayerToDown() {
        _move(0,1)
    }
    function movePlayerToLeft() {      
        _move(-1,0)
    }
    function movePlayerToRight() {
        _move(1,0)
    }
    
    return {
        player,
        movePlayerToUp,
        movePlayerToDown,
        movePlayerToLeft,
        movePlayerToRight
    }
})